<?php
class TemplateItem extends ORDataObject{
	var $template_item_id = '';
	var $template_id = '';
	var $medicine_id = '';	
	var $usage_num = '';
	var $usage_title = '';
	var $dosage = '';
	var $dosage_title = '';
	var $time = '';
	var $quantity_num = '';
	var $quantity_title = '';
	var $note = '';

	var $_table = 'template_item';
	var $_key = 'template_item_id';
	var $_internalName = 'TemplateItem';
	
	function TemplateItem(){
		parent::ORDataObject();		
	}
	
	function delete($templateId) {
		$sql = "DELETE FROM template_item WHERE template_id = $templateId";
		$this->_execute($sql);
	}
	
	function addNewTemplateItem($templateItem){			
		$data = array (
				'template_id'		    => 	$templateItem['template_id'],
				'medicine_id'			=> 	$templateItem['medicine_id'],
				'usage_title' 			=> 	$templateItem['usage_title'],
				'usage_num'				=> 	$templateItem['usage_num'],
				'dosage'				=> 	$templateItem['dosage'],
		        'dosage_title'          =>  $templateItem['dosage_title'],
				'time'					=> 	$templateItem['time'],
				'quantity_num'			=> 	$templateItem['quantity_num'],
				'quantity_title'		=> 	$templateItem['quantity_title'],
				'note'					=> 	$templateItem['note']				
			);		
		$this->populateArray($data);		
		$this->persist();							
		return $this->template_item_id;
	}
	
	function getTemplateItemsToImport($input){
		$sql = "SELECT pres.medicine_id, pres.medicine_name, pres.usage_title, pres.usage_num, 
					dosage, pres.time, pres.quantity_num, pres.quantity_title, mdu.usage_unit, pres.note".
			" FROM template_item pres 
				LEFT JOIN medicine med ON (pres.medicine_id = med.medicine_id) 
				LEFT JOIN medicine_default_usage mdu ON (mdu.id = med.default_usage_id)".	
			" WHERE (template_id = '".$input['template_id']."') 
				AND (pres.medicine_id NOT IN
						(SELECT medicine_id 
							FROM template_item 
							WHERE template_id = '".$input['template_id']."'))";
		// NGUYEN TODO: why NOT IN??	
		$result = $this->_db->GetAll($sql);
		return $result;
	}
	
	function getTemplateItems($templateId){						
		$sql = "SELECT template_item_id , template_id,  medicine_id, pd.proprietary_name AS medicine_name,
		      usage_title , usage_num, dosage , dosage_title, time, quantity_num , quantity_title, note
			 FROM $this->_table ti 
			 	LEFT JOIN drug_material pd ON (ti.medicine_id = pd.drug_material_id)
			 WHERE template_id = $templateId
			 ORDER BY template_item_id";					
		$result = $this->_db->GetAll($sql);
		return $result;
	}
}
?>